<template>
    <el-form ref="baseForm" :model="form" :rules="rules" label-width="100px">
        <el-row>
            <el-col :span="6">
            <el-form-item label="代码标识" prop="unitName">
                <el-input v-model="form.unitName"></el-input>
            </el-form-item>
            </el-col><el-col :span="6">
            <el-form-item label="名称" prop="name">
                <el-input v-model="form.name"></el-input>
            </el-form-item>
            </el-col>

            <el-col :span="6">
            <el-form-item label="分类" prop="categories">
                <dx-select v-model="form.categories" placeholder="请选择" codeType="CODE_MODEL_CATEGROIES"></dx-select> 
            </el-form-item>
            </el-col>
            <el-col :span="6">
            <el-form-item label="单元类型" prop="unitType">
                <dx-select v-model="form.unitType" :disabled="isEdit||(form.slaveDm!=null&&form.slaveDm.length>0)" placeholder="请选择" codeType="unitcomponent_type"></dx-select> 
            </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="6">
            <el-form-item label="主表" prop="masterDm">
                <dx-select v-model="form.masterDm" :disabled="isEdit||(form.slaveDm!=null&&form.slaveDm.length>0)" placeholder="请选择" codeType="datamodel_codelist" @change="masterChange"></dx-select> 
            </el-form-item>
            </el-col>
            <el-col :span="6">
            <el-form-item label="从表" prop="slaveDm">
                <dx-select v-model="form.slaveDm" :multiple="true" :disabled="isEdit || form.unitType!='master_slave'" placeholder="请选择" :condition="{module_name:form.masterDm}" @change="slaveChange" codeType="datamodel_codelist"></dx-select> 
            </el-form-item>
            </el-col>

            <el-col :span="6">
            <el-form-item label="排序" prop="orderList">
                <el-input v-model="form.orderList"></el-input>
            </el-form-item>
            </el-col>
            <el-col :span="6">
            <el-form-item label="启用" prop="enable">
                <el-switch v-model="form.enable"></el-switch>
            </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="6">
            <el-form-item label="显示序号" prop="lineNumber">
                <el-checkbox v-model="form.lineNumber"></el-checkbox>
            </el-form-item>
            </el-col>
            <el-col :span="6">
            <el-form-item label="显示复选框" prop="chkSelect">
                <el-checkbox v-model="form.chkSelect"></el-checkbox>
            </el-form-item>
            </el-col>

            <el-col :span="6">
            <el-form-item label="默认降序" prop="defaultSort">
                <dx-select v-model="form.defaultSort" :multiple="true" :clearable="true" codeType="datamodel_fields_codelist" :condition="{module_name:form.masterDm}"></dx-select>
            </el-form-item>
            </el-col>
            <el-col :span="6">
            <el-form-item label="列表数据源" prop="summaryDs">
                <dx-select v-model="form.summaryDs" :clearable="true" placeholder="请选择" :condition="{module_name:form.masterDm}" @change="slaveChange" codeType="datamodel_codelist"></dx-select> 
            </el-form-item>
            </el-col>
        </el-row>
        <el-row v-if="form.masterDm">
            <el-col :span="6">
            <el-form-item label="树代码模型" prop="treeCodeType">
                <dx-treeselect v-model="form.treeCodeType" :expandLevel="1" codeType="codemodel_treelist" 
                :leafable="true" :filterable="true" :clearable="true"></dx-treeselect>
            </el-form-item>
            </el-col>
            <el-col :span="6">
            <el-form-item label="树关联字段" prop="treeFieldKey">
                 <dx-select v-model="form.treeFieldKey" codeType="datamodel_fields_codelist" 
                 :condition="{module_name:form.summaryDs?form.summaryDs:form.masterDm}" :clearable="true"></dx-select>
            </el-form-item>
            </el-col>


            <el-col :span="6">
            <el-form-item label="树筛选类型" prop="treeFilterType">
                
                <el-select v-model="form.treeFilterType" :clearable="true">
                    <el-option v-for="(item,index) in [{name:'SQL筛选',value:'1'},{name:'静态筛选',value:'2'}]" :key="index" :label="item.name" :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            </el-col>
            <el-col :span="6">
            <el-form-item label="树筛选字段" prop="treeFilterFieldKey">
                <el-input :disabled="form.treeFilterType!='1'" :clearable="true" v-model="form.treeFilterFieldKey"></el-input>
            </el-form-item>
            </el-col>
            
        </el-row>
        <el-row>
            <el-col :span="12">
            <el-form-item label="过滤条件" prop="filterSql">
                <el-input v-model="form.filterSql" type="textarea" :rows="4"></el-input>
            </el-form-item>
            </el-col>
            <el-col :span="12">
            <el-form-item label="基础按钮" prop="buttons">
                <el-checkbox-group v-model="form.buttons">
                    <el-checkbox label="Add"></el-checkbox>
                    <el-checkbox label="Edit"></el-checkbox>
                    <el-checkbox label="View"></el-checkbox>
                    <el-checkbox label="Delete"></el-checkbox>
                    <el-checkbox label="Query"></el-checkbox>
                    <el-checkbox label="ExportExcel"></el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            
            </el-col>
            
        </el-row>

        <el-row>
             <el-tabs v-if="form.masterDm!=null" v-model="activeName" type="border-card">
                <el-tab-pane v-for="(item,index) in tables" :key="index">
                    <span slot="label"><dx-text :value="item.datamodelName" codeType='datamodel_codelist'></dx-text>({{item.datamodelName}})</span>
                    
                    <el-tabs :value="Add" type="border-card">
                        <el-tab-pane v-for="(op,index) in item.datamodelName==form.masterDm?['Add','Edit','Summary','View']:['Add','Edit','View']" :key="index">
                            <span slot="label">{{op}}</span>

                            <el-button type="primary" size="small" @click="addRow(item,op)" style="margin-bottom:10px;"><i class="el-icon-plus"></i>增加字段</el-button> | 
                            <el-button type="primary" v-for="(b,bi) in ['Add','Edit','View','Summary'].filter(n=>{return n!=op})" size="small" @click="copyFields(item,b,op)" style="margin-bottom:10px;" :key="op+bi">复制{{b}}字段信息</el-button>
                            

                            <el-table :data="item[opMap[op]]" border stripe style="width:100%;" :key="index">
                                <el-table-column label="字段" width="150" fixed align="center">
                                    <template slot-scope="scope">
                                        <dx-select v-model="scope.row.columnName" codeType="datamodel_fields_codelist" :condition="{module_name:(op=='Summary'&&form.summaryDs)?form.summaryDs:item.datamodelName}" 
                                        @change="columnNameChange($event ,scope.$index ,scope.row)" :clearable="true"></dx-select>
                                    </template>
                                </el-table-column>
                                <el-table-column label="名称" width="150" align="center">
                                    <template slot-scope="scope">
                                        <el-input v-model="scope.row.columnLabel"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="代码模型" width="180" align="center">
                                    <template slot-scope="scope">
                                        <dx-treeselect v-model="scope.row.codeType" :expandLevel="1" codeType="codemodel_treelist" :leafable="true" :filterable="true" :clearable="true"></dx-treeselect>
                                    </template>
                                </el-table-column>
                                <el-table-column label="控件" width="180" align="center">
                                    <template slot-scope="scope">
                                       <dx-select v-model="scope.row.ctrlName" codeType="static_resource_codelist" :condition="{staticType:'ctrl'}"></dx-select>
                                    </template>
                                </el-table-column>
                                <el-table-column label="备注" width="150" align="center">
                                    <template slot-scope="scope">
                                        <el-input v-model="scope.row.remark"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="级联字段" width="150" align="center">
                                    <template slot-scope="scope">
                                        <dx-select v-model="scope.row.cascadeField" codeType="datamodel_fields_codelist" :clearable="true"
                                        :condition="{module_name:(op=='Summary'&&form.summaryDs)?form.summaryDs:item.datamodelName}"></dx-select>
                                    </template>
                                </el-table-column>
                                <el-table-column label="宽度" width="100" align="center">
                                    <template slot-scope="scope">
                                       <el-input v-model="scope.row.width"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="可见" width="100" align="center">
                                    <template slot-scope="scope">
                                        <dx-select v-model="scope.row.visible" codeType="static_resource_codelist" :clearable="true" :condition="{staticType:'visible'}"></dx-select>
                                    </template>
                                </el-table-column>
                                <el-table-column label="排序" width="100" align="center">
                                    <template slot-scope="scope">
                                       <el-input v-model="scope.row.orderList"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="格式化" align="center" width="160">
                                    <template slot-scope="scope">
                                        <el-select v-model="scope.row.formatter" :clearable="true">
                                                <el-option v-for="(item,index) in ['df_short','df_long']" :key="index" :value="item" :label="item"></el-option>
                                            </el-select>
                                    </template>
                                </el-table-column>
                                <template v-if="in_array(op,['Add','Edit','View'])">
                                    <el-table-column label="补全簇字段" width="150" align="center">
                                        <template slot-scope="scope">
                                            <dx-select v-model="scope.row.autocompleteField" codeType="datamodel_fields_codelist" :clearable="true"
                                            :condition="{module_name:item.datamodelName}"></dx-select>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="多选个数" width="80" align="center">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.multiAmount"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="校验器" align="center" width="100">
                                        <template slot-scope="scope">
                                             <dx-select v-model="scope.row.validators" codeType="static_resource_codelist" :clearable="true" :condition="{staticType:'validators'}"></dx-select>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="正则" width="150" align="center">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.regex"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="错误提示" width="150" align="center">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.regexMsg"></el-input>
                                        </template>
                                    </el-table-column>
                                    
                                    <el-table-column label="默认值" width="120" align="center">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.defaultValue"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="唯一" width="50" align="center">
                                        <template slot-scope="scope">
                                            <el-checkbox v-model="scope.row.isUnique"></el-checkbox>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="忽略检查选项" width="50" align="center">
                                        <template slot-scope="scope">
                                            <el-checkbox v-model="scope.row.ignoreCheckOptions"></el-checkbox>
                                        </template>
                                    </el-table-column>
                                    
                                    <el-table-column label="占列" align="center" width="120">
                                        <template slot-scope="scope">
                                             <el-select v-model="scope.row.span">
                                                 <el-option v-for="(item,index) in [{name:'1行2列',value:1},{name:'1行1列',value:2}]" :key="index" :value="item.value" :label="item.name"></el-option>
                                             </el-select>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="placeholder" width="100" align="center">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.placeholder"></el-input>
                                        </template>
                                    </el-table-column>
                                </template>
                                <template v-if="op=='Summary'">
                                    <el-table-column label="可搜索" align="center" width="80">
                                        <template slot-scope="scope">
                                            <el-checkbox v-model="scope.row.filterable"></el-checkbox>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="对齐" width="120" align="center">
                                        <template slot-scope="scope">
                                            <dx-select v-model="scope.row.align" codeType="static_resource_codelist" :clearable="true" :condition="{staticType:'align'}"></dx-select>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="可排序" align="center" width="80">
                                        <template slot-scope="scope">
                                            <el-checkbox v-model="scope.row.sortable"></el-checkbox>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="固定" align="center" width="80">
                                        <template slot-scope="scope">
                                            <el-checkbox v-model="scope.row.fixed"></el-checkbox>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="条件" align="center" width="120">
                                        <template slot-scope="scope">
                                            <dx-select v-model="scope.row.express" :disabled="!scope.row.filterable" codeType="static_resource_codelist" :clearable="true" :condition="{staticType:'express'}"></dx-select>
                                        </template>
                                    </el-table-column>

                                </template>
                                


                                <el-table-column label="操作" width="80" align="center">
                                    <template slot-scope="scope">
                                        <el-button type="text" size="small" @click="deleteRow(item,op,scope.$index,scope.row)">移除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>


                        </el-tab-pane>
                    </el-tabs>

                    
                </el-tab-pane>
            </el-tabs>

           <br>
        </el-row>
        <el-row v-if="form.slaveDm!=null && form.slaveDm.length>0">
             <el-col :span="8">
                <el-button type="primary" size="small" @click="addRelationRow" style="margin-bottom:10px;"><i class="el-icon-plus"></i>增加关联关系</el-button>
                <el-table :data="relationTableData" border stripe style="width:100%;" :key="index">
                    <el-table-column label="主表KEY" >
                        <template slot-scope="scope">
                            <dx-select v-model="scope.row.masterKey" codeType="datamodel_fields_codelist" :condition="{module_name : form.masterDm}"></dx-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="从表" prop="slaveTable">
                        <template slot-scope="scope">
                            <el-select v-model="scope.row.slaveTable">
                                <el-option v-for="(item,index) in form.slaveDm" :key="index" :value="item" :label="item"></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="从表KEY" prop="slaveKey">
                        <template slot-scope="scope">
                            <dx-select v-model="scope.row.slaveKey" codeType="datamodel_fields_codelist" :condition="{ module_name : scope.row.slaveTable}"></dx-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80">
                        <template slot-scope="scope">
                            <el-button type="text" size="small" @click="deleteRelationRow(scope.$index,scope.row)">移除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
             </el-col>
            <br>
        </el-row>
        <div style="width:150px;margin:20px auto;">
            <el-button type="primary" :loading="isLoading" @click="doSubmit"><span v-if="!isEdit">立即创建</span><span v-else>保存</span></el-button>
            <el-button @click="closeDialog">取消</el-button>
        </div>

    </el-form>
</template>
<script>
import DxSelect from '../../Common/ui/dx-select'
import DxCheckBox from '../../Common/ui/dx-checkbox'
import DxRadio from '../../Common/ui/dx-radio'
import DxText from '../../Common/ui/dx-text'
import DxSuggesttext from '../../Common/ui/dx-suggesttext'
import DxTreeselect from '../../Common/ui/dx-treeselect'
import http from '../../../assets/js/http.js'
import toolkit from '../../../assets/js/toolkit.js'
import {codeProvider} from '../../../assets/js/provider.js'

let inTables = (tables,datamodelName) =>{
    for(let i=0;i<tables.length;i++){
        if(tables[i].datamodelName == datamodelName){
            return i;
        }
    }
    return -1;

}
export default {

    components : {
        DxSelect,
        DxCheckBox,
        DxRadio,
        DxText,
        DxSuggesttext,
        DxTreeselect
    },
    props :{
        id : String,
    },
    watch : {

        
    },
    data(){
        return {
            opMap : {Add:'addFields',Edit:'editFields',Summary:'summaryFields',View:'viewFields'},
            tables : [],
            activeName : '',
            dialogVisible : false,
            isloading : false,
            isCompileLoading : false,
            isEdit : false,
            relationTableData : [],
            fields : {},
            form : {
                id : this.id,
                unitName : '',
                summaryDs : '',
                name : '',
                unitType : 'single',
                categories : '1',
                masterDm : null,
                slaveDm : [],
                orderList : 10,
                enable : true,
                relation : "",
                buttons : [],
                filterSql : "",
                defaultSort : [],
                summaryDs : '',
                dmAlias : '',
                lineNumber : '',
                chkSelect : '',
            },
            rules: {
                unitName : [{ required: true, message: '请输入单元组件标识', trigger: 'blur' },
                            {pattern: /^[A-Za-z0-9_]+$/, message: '请输入英文字母', trigger: 'blur'}],
                name : [{ required: true, message: '请输入单元组件名称', trigger: 'blur' }],
                masterDm : [{ required: true, message: '请选择主表', trigger: 'change' }],
                unitType : [{ required: true, message: '请选择单元组件类型', trigger: 'change' }],
                categories : [{ required: true, message: '请选择分类', trigger: 'change' }]
            }
        }
    },
    methods : {
        addRow(item,op){
            let lastEl = {orderList:0};
            let data = item[this.opMap[op]];
            if(data && data.length>0){
                lastEl = data[data.length-1];
            }   
            item[this.opMap[op]].push({orderList: lastEl.orderList + 10});
        },
        deleteRow(item,op,index,row){
            item[this.opMap[op]].splice(index,1);
        },
        columnNameChange(val,index,row){
            if(val){
                
                row.columnLabel = val.other.column_label;
                row.codeType = val.other.code_type;
            }else{
                row.columnLabel = '';
                row.codeType = '';
            }
            
        },
        addRelationRow(){
            this.relationTableData.push({});
        },
        deleteRelationRow(index,row){
            this.relationTableData.splice(index,1);
        },

        copyFields(item,distOp,op){

            item[this.opMap[op]] = [];
            item[this.opMap[distOp]].forEach(mItem=>{
              
                let clone = Object.assign({},mItem);
                clone.viewType = op.toLowerCase();
                clone.id = "";
                item[this.opMap[op]].push(clone);
            });
        },
        doSubmit(){

             this.$refs.baseForm.validate(vaild=>{

                if(vaild){
                    if(this.isEdit){
                        this.update();   
                    }else{
                        this.save();
                    }
                }
            });
          
        },

        update(){

            this.isLoading = !this.isLoading
            let _data = Object.assign({},this.form);
            _data.isSystem = this.form.isSystem?this.form.isSystem:0;
            _data.modifyDate = moment(this.form.modifyDate).format('YYYY-MM-DD HH:mm:ss');
            _data.createDate = moment(this.form.createDate).format('YYYY-MM-DD HH:mm:ss');
            _data.slaveDm = _.join(_data.slaveDm,",");
            _data.defaultSort = _.join(_data.defaultSort,",");

            
            _data.buttons = _.join(_data.buttons,",");
            _data.relation = JSON.stringify(this.relationTableData);

          
            _data.fields = this.getUpdateFields();


            delete _data.tables;
            delete _data.tableRelations;
            
            this.apiPostForm('unit/updateSave',_data).then(resp=>{
                this.isLoading = !this.isLoading
                if(resp.code==200){
                    _g.toastMsg('success', '保存成功')
                    this.closeDialog();
                    this.$emit('submitData','update'); 
                }else{
                    _g.toastMsg('error',resp.msg);
                }
                
            });
        },
        getUpdateFields(){
            let fields = [];
            let markViewType = (fields,type) => {
                fields.forEach(field=>{
                    field.viewType = type;
                });
                return fields;
            }
            this.tables.forEach(t=>{

           
                let addFields = markViewType(t.addFields || [],'add');
        
                let editFields = markViewType(t.editFields || [],'edit');
                let summaryFields = markViewType(t.summaryFields || [],'summary');
                let viewFields = markViewType(t.viewFields || [],'view');
                                 
                let datamodelName = t.datamodelName;
                let tableType = t.tableType;
                let allFields = [...addFields,...editFields,...summaryFields,...viewFields];
                allFields.forEach(field=>{
                    let clone = Object.assign({},field);
                    clone.datamodelName = datamodelName||"";
                    clone.tableType = tableType||"";
                    for(let p in clone){
                        if(!clone[p]){
                            clone[p] = "";
                        }
                    }
                    fields.push(clone);
                });
                
            });
            return fields;
        },
        save(){
            this.isLoading = !this.isLoading
            let _data = Object.assign({},this.form);
            _data.id = 0;
      

            _data.buttons = _.join(_data.buttons,",");
            _data.slaveDm = _.join(_data.slaveDm,",");
            _data.defaultSort = _.join(_data.defaultSort,",");

            // console.log('tables',this.tables);
            _data.fields = this.getUpdateFields();

            _data.relation = JSON.stringify(this.relationTableData);

            delete _data.tables;
            delete _data.tableRelations;
            // console.log(_data);

            this.apiPostForm('unit/addSave',_data).then(resp=>{

                this.isLoading = !this.isLoading
                if(resp.code==200){
                    _g.toastMsg('success', '保存成功')
                    this.closeDialog();
                    this.$emit('submitData','update'); 
                }else{
                    _g.toastMsg('error',resp.msg);
                }
                
            });
        },
        closeDialog(){
            this.$emit('update:dialogVisible', false);
        },
        
        initData(){

            if(this.form.id){
                this.isEdit = true;
                _g.openGlobalLoading();
                this.apiGet('unit/getEntry?id='+this.form.id).then(resp=>{
                     _g.closeGlobalLoading();
                    if(resp.code == 200){
                        this.form = resp.data;
     
                        this.form.slaveDm = this.form.slaveDm ? this.form.slaveDm.split(",") : [];
                        this.form.buttons = this.form.buttons ? this.form.buttons.split(",") : [];
                        
                        this.form.defaultSort = this.form.defaultSort ? this.form.defaultSort.split(",") : [];

                        this.relationTableData = this.form.tableRelations;
                        this.masterChange();

                        this.slaveChange();

                        (resp.data.tables||[]).forEach(t=>{

                            let index = 0;
                            if((index = inTables(this.tables ,t.datamodelName)) >= 0){
                                this.tables[index] = t;
                            }
                        });
                    }else{
                        _g.toastMsg("warn",resp.msg);
                        setTimeout(()=>{
                            this.dialogVisible = false;
                        },1000);
                    }
                   
                });
            }else{
                this.isEdit = false;
            }
        },
        masterChange(val){
            let empty = {
                        datamodelName : this.form.masterDm,
                        tableType : 'master',
                        addFields : [],
                        editFields : [],
                        summaryFields : [],
                        viewFields : []
                    };
            let index = 0;
            let tmp = [...this.tables];
            this.tables = [];
            this.tables.push(empty);
            tmp.forEach(item=>{
                if(item.tableType=='slave'){
                    this.tables.push(item);
                }
            });
            this.activeName = '0';
        },
        slaveChange(val){
         
            let index = 0;
            let tmp = [...this.tables];

            this.tables = [];

            tmp.forEach(item=>{
                if(item.tableType=='master'){
                    this.tables.push(item);
                }
            });

            (this.form.slaveDm ||[]).forEach(item=>{
                let empty = {
                        datamodelName : item,
                        tableType : 'slave',
                        addFields : [],
                        editFields : [],
                        summaryFields : [],
                        viewFields : []
                    };   
                this.tables.push(empty);
            });
            this.activeName = '0';
   
        }
    },
    created(){
        this.initData();
    },
    mounted(){
        this.routeName = this.$route.name;
        _g.closeGlobalLoading();
    },
    mixins:[http,toolkit]
}
</script>

<style scoped>
@import '../../../assets/css/framework.css';
/* .el-scrollbar{
    width: 400px;
} */
</style>
